package dyyx.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import dyyx.dto.CmdDTO;

/**
 * 用户执行shell命令 获取返回结果
 * @author dugang
 *
 */
public abstract class ShellUtil{
	
	
	public static void execute(CmdDTO dto) throws Exception {
		if (dto == null) {
			return;
		}
		String cmd = dto.cmd;
		if (CommUtil.isBlank(cmd)) {
			throw new RuntimeException("cmd is blank");
		}
		//
		Process process = null;
		BufferedReader br = null;
		BufferedReader brerror = null;

		try {
			process = Runtime.getRuntime().exec(cmd, null, null);

			// 等待命令执行完成成功返回0
			int result = process.waitFor();
			dto.result = result;

			// 获取命令执行结果,正常的输出 和 错误的输出

			br = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
			brerror = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"));

			String line = null;
			StringBuilder infosb = new StringBuilder();

			while ((line = br.readLine()) != null) {
				infosb.append(line).append('\n');
			}
			StringBuilder errorsb = new StringBuilder();

			while ((line = brerror.readLine()) != null) {
				errorsb.append(line).append('\n');
			}

			dto.info = infosb.toString();
			dto.error = errorsb.toString();
			
			// process.destroy();

		} finally {
			CommUtil.close(br);
			CommUtil.close(brerror);
			destroyProcess(process);
		}

	}
	
	private static void destroyProcess(Process process){
		if(process==null){
			return;
		}
		//
		try{
			process.destroy();
		}catch(Throwable e){
			//
			
		}
	}
	
	
	
	
}
